
// 图表实例
let usageTrendChart, responseChart;
let currentPeriod = 'month';
let currentResponseView = 'success';

// 测试数据
let testData = {};
export function init(){

    testData = {
        // 按日统计数据
        day: {
            labels: Array.from({length: 24}, (_, i) => `${i}:00`),
            data: Array.from({length: 24}, () => Math.floor(Math.random() * 50) + 20),
            successRate: Array.from({length: 24}, () => Math.random() * 0.1 + 0.85), // 85%-95%
            responseTimes: Array.from({length: 24}, () => Math.random() * 0.8 + 0.8) // 0.8-1.6s
        },
        // 按周统计数据
        week: {
            labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            data: Array.from({length: 7}, () => Math.floor(Math.random() * 200) + 100),
            successRate: Array.from({length: 7}, () => Math.random() * 0.1 + 0.85),
            responseTimes: Array.from({length: 7}, () => Math.random() * 0.5 + 0.9)
        },
        // 按月统计数据
        month: {
            labels: Array.from({length: 30}, (_, i) => `${i+1}日`),
            data: Array.from({length: 30}, () => Math.floor(Math.random() * 40) + 20),
            successRate: Array.from({length: 30}, () => Math.random() * 0.1 + 0.85),
            responseTimes: Array.from({length: 30}, () => Math.random() * 0.6 + 0.8)
        },
        // 错误类型数据
        errorTypes: {
            labels: ['超时错误', '格式错误', '权限不足', '参数错误', '系统错误'],
            data: [15, 12, 8, 6, 3]
        },
        // 调用记录数据
        callRecords: [
            {time: '2023-10-15 14:30:22', user: '张三', type: '公文生成', response: 1.2, status: 'success', error: null},
            {time: '2023-10-15 14:25:18', user: '李四', type: '公文校对', response: 0.8, status: 'success', error: null},
            {time: '2023-10-15 14:20:05', user: '王五', type: '公文生成', response: 2.1, status: 'warning', error: '部分内容未生成'},
            {time: '2023-10-15 14:15:42', user: '赵六', type: '模板下载', response: 1.5, status: 'success', error: null},
            {time: '2023-10-15 14:10:33', user: '钱七', type: '公文生成', response: 3.2, status: 'error', error: '模板ID不存在'},
            {time: '2023-10-15 14:05:21', user: '孙八', type: '公文校对', response: 1.8, status: 'success', error: null},
            {time: '2023-10-15 14:00:15', user: '周九', type: '公文生成', response: 2.5, status: 'warning', error: '缺少必要参数'},
            {time: '2023-10-15 13:55:42', user: '吴十', type: '模板下载', response: 0.9, status: 'success', error: null},
            {time: '2023-10-15 13:50:37', user: '郑十一', type: '公文生成', response: 1.7, status: 'success', error: null},
            {time: '2023-10-15 13:45:22', user: '王十二', type: '公文校对', response: 2.3, status: 'error', error: '文件格式不支持'}
        ]
    };
    // 初始化日期选择器
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

    document.getElementById('startDate').valueAsDate = firstDayOfMonth;
    document.getElementById('endDate').valueAsDate = today;

    // 初始化图表
    initUsageTrendChart();
    initResponseChart();
    renderCallRecords();

    // 绑定事件
    bindEvents();
}


function initUsageTrendChart() {
    const ctx = document.getElementById('usageTrendChart').getContext('2d');

    usageTrendChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: testData[currentPeriod].labels,
            datasets: [{
                label: '调用量',
                data: testData[currentPeriod].data,
                backgroundColor: 'rgba(33, 136, 255, 0.1)',
                borderColor: 'rgba(33, 136, 255, 1)',
                borderWidth: 2,
                tension: 0.3,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

function initResponseChart() {
    const ctx = document.getElementById('responseChart').getContext('2d');

    responseChart = new Chart(ctx, {
        type: currentResponseView === 'error' ? 'pie' : 'bar',
        data: getResponseChartData(),
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: currentResponseView === 'error' ? 'right' : 'top'
                }
            },
            scales: currentResponseView === 'error' ? {} : {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

function getResponseChartData() {
    if (currentResponseView === 'success') {
        return {
            labels: testData[currentPeriod].labels,
            datasets: [{
                label: '成功率 (%)',
                data: testData[currentPeriod].successRate.map(rate => (rate * 100).toFixed(1)),
                backgroundColor: 'rgba(40, 167, 69, 0.7)',
                borderColor: 'rgba(40, 167, 69, 1)',
                borderWidth: 1
            }]
        };
    } else if (currentResponseView === 'time') {
        return {
            labels: testData[currentPeriod].labels,
            datasets: [{
                label: '响应时间 (秒)',
                data: testData[currentPeriod].responseTimes,
                backgroundColor: 'rgba(255, 160, 0, 0.7)',
                borderColor: 'rgba(255, 160, 0, 1)',
                borderWidth: 1
            }]
        };
    } else {
        return {
            labels: testData.errorTypes.labels,
            datasets: [{
                data: testData.errorTypes.data,
                backgroundColor: [
                    'rgba(220, 53, 69, 0.7)',
                    'rgba(253, 126, 20, 0.7)',
                    'rgba(255, 193, 7, 0.7)',
                    'rgba(13, 110, 253, 0.7)',
                    'rgba(108, 117, 125, 0.7)'
                ],
                borderColor: [
                    'rgba(220, 53, 69, 1)',
                    'rgba(253, 126, 20, 1)',
                    'rgba(255, 193, 7, 1)',
                    'rgba(13, 110, 253, 1)',
                    'rgba(108, 117, 125, 1)'
                ],
                borderWidth: 1
            }]
        };
    }
}

function renderCallRecords() {
    const container = document.getElementById('callRecords');
    container.innerHTML = '';

    testData.callRecords.forEach(record => {
        const row = document.createElement('tr');

        // 状态徽章
        let statusBadge;
        if (record.status === 'success') {
            statusBadge = '<span class="status-badge success">成功</span>';
        } else if (record.status === 'warning') {
            statusBadge = '<span class="status-badge warning">部分成功</span>';
        } else {
            statusBadge = '<span class="status-badge error">失败</span>';
        }

        // 查看详情按钮
        let actionBtn = '<a href="#" class="view-detail">查看详情</a>';
        if (record.status === 'success') {
            actionBtn = '<a href="#">查看结果</a>';
        }

        row.innerHTML = `
                    <td>${record.time}</td>
                    <td>
                        <div class="user-cell">
                            <div class="user-avatar">${record.user.charAt(0)}</div>
                            <div>${record.user}</div>
                        </div>
                    </td>
                    <td>${record.type}</td>
                    <td>${record.response}s</td>
                    <td>${statusBadge}</td>
                    <td>${actionBtn}</td>
                `;

        container.appendChild(row);
    });

    // 绑定查看详情事件
    document.querySelectorAll('.view-detail').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const rowIndex = Array.from(this.closest('tbody').children).indexOf(this.closest('tr'));
            const record = testData.callRecords[rowIndex];

            const detailContainer = document.getElementById('errorDetailContainer');
            const detailContent = document.getElementById('errorDetailContent');

            detailContent.textContent = record.error || '无错误详情';
            detailContainer.style.display = 'block';

            // 滚动到详情区域
            detailContainer.scrollIntoView({behavior: 'smooth'});
        });
    });
}

function bindEvents() {
    // 周期选择按钮切换
    document.querySelectorAll('.period-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.period-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            currentPeriod = this.dataset.period;
            updateCharts();
        });
    });

    // 图表切换按钮
    document.querySelectorAll('.chart-toggle-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const parent = this.closest('.chart-toggle');
            parent.querySelectorAll('.chart-toggle-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            if (this.closest('.chart-header').querySelector('.chart-title').textContent === '调用量趋势') {
                // 调用量趋势图表切换
                const type = this.dataset.type;
                if (type === 'day') currentPeriod = 'day';
                else if (type === 'week') currentPeriod = 'week';
                else currentPeriod = 'month';
            } else {
                // 响应时间图表切换
                currentResponseView = this.dataset.type;
            }

            updateCharts();
        });
    });

    // 应用日期范围
    document.getElementById('applyDateBtn').addEventListener('click', function() {
        alert('日期范围已应用');
        // 实际应用中这里应该重新加载数据
    });

    // 导出按钮
    document.getElementById('exportReportBtn').addEventListener('click', function() {
        alert('导出完整报表功能将在实际应用中实现');
    });

    document.getElementById('exportCsvBtn').addEventListener('click', function() {
        alert('导出CSV功能将在实际应用中实现');
    });

    document.getElementById('exportTrendImage').addEventListener('click', function() {
        const image = usageTrendChart.toBase64Image();
        const link = document.createElement('a');
        link.href = image;
        link.download = '调用量趋势.png';
        link.click();
    });

    document.getElementById('exportTrendData').addEventListener('click', function() {
        alert('调用量趋势数据导出功能将在实际应用中实现');
    });

    document.getElementById('exportResponseImage').addEventListener('click', function() {
        const image = responseChart.toBase64Image();
        const link = document.createElement('a');
        link.href = image;
        link.download = '响应分析.png';
        link.click();
    });

    document.getElementById('exportResponseData').addEventListener('click', function() {
        alert('响应分析数据导出功能将在实际应用中实现');
    });

    // 全屏按钮
    document.getElementById('fullscreenTrend').addEventListener('click', function() {
        alert('调用量趋势图表全屏功能将在实际应用中实现');
    });

    document.getElementById('fullscreenResponse').addEventListener('click', function() {
        alert('响应分析图表全屏功能将在实际应用中实现');
    });

    // 返回按钮
    document.getElementById('backBtn').addEventListener('click', function() {
        alert('返回上一页功能将在实际应用中实现');
    });

    // 分页按钮
    document.getElementById('prevPageBtn').addEventListener('click', function() {
        alert('上一页功能将在实际应用中实现');
    });

    document.getElementById('nextPageBtn').addEventListener('click', function() {
        alert('下一页功能将在实际应用中实现');
    });
}

function updateCharts() {
    // 更新调用量趋势图表
    usageTrendChart.data.labels = testData[currentPeriod].labels;
    usageTrendChart.data.datasets[0].data = testData[currentPeriod].data;
    usageTrendChart.update();

    // 更新响应图表
    if (currentResponseView === 'error') {
        responseChart.destroy();
        initResponseChart();
    } else {
        responseChart.data = getResponseChartData();
        responseChart.update();
    }

    // 更新统计数据
    updateStats();
}

function updateStats() {
    const data = testData[currentPeriod].data;
    const total = data.reduce((sum, val) => sum + val, 0);
    const success = Math.floor(total * 0.95);
    const failed = total - success;
    const avgResponse = (testData[currentPeriod].responseTimes.reduce((sum, val) => sum + val, 0) / testData[currentPeriod].responseTimes.length).toFixed(1);

    document.getElementById('totalCalls').textContent = total.toLocaleString();
    document.getElementById('successCalls').textContent = success.toLocaleString();
    document.getElementById('failedCalls').textContent = failed.toLocaleString();
    document.getElementById('avgResponse').textContent = `${avgResponse}s`;

    // 随机生成变化百分比
    document.getElementById('totalChange').textContent = `${(Math.random() * 10 + 5).toFixed(1)}%`;
    document.getElementById('successChange').textContent = `${(Math.random() * 8 + 3).toFixed(1)}%`;
    document.getElementById('failedChange').textContent = `${(Math.random() * 5).toFixed(1)}%`;
    document.getElementById('responseChange').textContent = `${(Math.random() * 0.3 + 0.1).toFixed(1)}s`;
}